﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Facebook;
using Mime;

namespace FeedBack {
    public class DefaultStatusDownloader : IDownloader {

        public event EventHandler<StoryDownloadedEventArgs> Completed;

        public void Download(Story story) {
            string dir = Configuration.InProgressFolder;
            string filename = CandidateFileName(story);
            string path = Path.Combine(dir, filename);
            dir.EnsureDirectory();
            
            string status = (story.Message ?? story.StoryName).Replace("\n", "\r\n");
            JsonObject place = story.Json.Get("place");
            if (place != null){
                status = string.Format("{1}\r\n\r\n{0}", status, place.Get<string>("name"));
            }
            File.WriteAllText(path, status);

            if (Completed != null) {
                Completed(this, new StoryDownloadedEventArgs { Filename = path, Story = story, Success = true });
            }

        }

        public string CandidateFileName(Story story) {
            var value = (story.Message ?? story.StoryName).RemoveIllegalPathCharacters();
            return value.Substring(0, Math.Min(value.Length, 50)) + ".txt";
        }

        public void PostProcess(string storyDirectory, Story story) {

        }
    }
}
